﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleRest.Serialization.Attributes.Annotations
{
    [AttributeUsage(AttributeTargets.Property)]
    public class FractionDigitsAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
    {
        private static List<Type> ValidTypes = new List<Type>()
        {
            typeof(decimal),
            typeof(float),
            typeof(double)
        };
        public readonly int MaximumDigigs;

        public FractionDigitsAttribute(int maxDigits)
        {
            this.MaximumDigigs = maxDigits;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
                throw new ArgumentNullException("Null is not a valid value.");

            if (!ValidTypes.Contains(value.GetType()))
                throw new ArgumentException("The value specified is not of the correct type to determine decimal digits.");

            string val = value.ToString().Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[1];
            if (val == null && this.MaximumDigigs == 0)
                return true;

            if (val.Length > this.MaximumDigigs)
                return false;
            return true;
        }
    }
}
